package com.ciko.code.fragment;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Handler;
import android.os.Message;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.ciko.code.adapter.WorkTypeAdapter;
import com.ciko.code.base.BaseFragment;
import com.ciko.code.http.BaseResponse;
import com.ciko.code.http.Req.SelUserPostInfoListEty;
import com.ciko.code.http.Req.UploadImgForWorkFlowReq;
import com.ciko.code.http.Req.submitMyPlanReq;
import com.ciko.code.utils.Util;
import com.ciko.code.utils.Utils;
import com.ciko.code.views.multi_image_selector.MultiImageSelectorActivity;
import com.image_see.ImageSeeActivity;
import com.mywork.R;
import com.mywork.activity.ChooseSupActivity;
import com.mywork.activity.FillOutWorkPlaneActivity;

import java.util.ArrayList;


/**
 * Created by 12154 on 2015/11/10.
 */
public class WorkPlaneMyFragment
        extends
        BaseFragment
        implements
        OnItemClickListener
{
	
	private TextView			   tv_finish;
	private TextView			   tv_type;
	private TextView			   tv_zongjie;
	private TextView			   tv_jihua;
	private TextView			   tv_bangzhu;
	private TextView			   tv_beizhu;
	private TextView			   tv_plane_man;
	private TextView			   tv_location;
	private TextView			   zongjie_tv;
	private TextView			   jihua_tv;
	private ImageView			   fujian_iv;
	private SelUserPostInfoListEty postInfo;
	private String				   completeWork;
	private String				   workSummary;
	private String				   workPlan;
	private String				   help;
	private String				   remarks;
	private String				   enclosure;
	private String				   address;
	private String				   str				  = "";
	submitPlaneCallBack			   callBack;
	private RelativeLayout		   rlImg;
	private static final int	   REQUEST_IMAGE	  = 7;
	private final int			   PIC_MAX_LENGTH	  = 1;
	private ArrayList<String>	   selectedPictureAll = new ArrayList<String>();
	private ArrayList<String>	   mSelectPath;
	private ArrayList<String>	   urlList			  = new ArrayList<>();
	private PopupWindow			   planPopWindow;
								   
	private int					   currentType		  = 1;						//1周报；2月报；3季报；4其他
	private ImageView			   imgDisplay;
								   
	public String getAddress() {
		return address;
	}
	
	public void setAddress(String address) {
		this.address = address;
	}
	
	private Handler workPlanHandler = new Handler()
	{
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
		}
	};
	
	@Override
	protected void initTopBar() {
		unableNav();
	}
	
	@Override
	protected void initLayout() {
		setContentView(R.layout.fragment_work_plane_my);
		screenWidth = getActivity().getApplicationContext().getResources().getDisplayMetrics().widthPixels;
	}
	
	@Override
	protected void initView() {
		tv_type = findViewById(R.id.tv_typeName);
		//        tv_finish = findViewById(R.id.tv_finish);
		tv_zongjie = findViewById(R.id.tv_zongjie);
		tv_jihua = findViewById(R.id.tv_jihua);
		tv_bangzhu = findViewById(R.id.tv_bangzhu);
		tv_beizhu = findViewById(R.id.tv_beizhu);
		tv_plane_man = findViewById(R.id.tv_plane_man);
		tv_location = findViewById(R.id.tv_location_address);
		zongjie_tv = findViewById(R.id.zongjie_tv);
		jihua_tv = findViewById(R.id.jihua_tv);
		fujian_iv = findViewById(R.id.plane_my_image);
		
		tv_location.setText(address);
		rlImg = findViewById(R.id.rl_img);
		imgDisplay = findViewById(R.id.plan_my_display);
		
	}
	
	public int screenWidth;
	
	void initPopWindow() {
		ArrayList<String> typeName = new ArrayList<>();
		typeName.add("周报");
		typeName.add("月报");
		typeName.add("季报");
		// 获取自定义布局文件activity_popupwindow_left.xml的视图
		View popupWindow_view = getActivity().getLayoutInflater().inflate(R.layout.plan_popwindow_layout, null, false);
		ListView typeListView = (ListView) popupWindow_view.findViewById(R.id.plan_type_listview);
		typeListView.setOnItemClickListener(this);
		typeListView.setFocusable(true);
		typeListView.setFocusableInTouchMode(true);
		typeListView.setDivider(new ColorDrawable(Color.GRAY));
		typeListView.setCacheColorHint(Color.TRANSPARENT);
		typeListView.setDividerHeight(1);
		WorkTypeAdapter mAdapter = new WorkTypeAdapter(getActivity(), typeName, R.layout.item_workpaln_popupwindow);
		typeListView.setAdapter(mAdapter);
		mAdapter.notifyDataSetChanged();
		
		// 创建PopupWindow实例,200,LayoutParams.MATCH_PARENT分别是宽度和高度
		planPopWindow = new PopupWindow(popupWindow_view, screenWidth / 2, ViewGroup.LayoutParams.WRAP_CONTENT, true);
		// 设置动画效果
		planPopWindow.setAnimationStyle(R.style.AnimationFade);
		// 点击其他地方消失
		popupWindow_view.setOnTouchListener(new OnTouchListener()
		{
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				hidePopupWindow();
				return false;
			}
		});
	}
	
	private void hidePopupWindow() {
		if (planPopWindow != null && planPopWindow.isShowing())
		{
			planPopWindow.dismiss();
			planPopWindow = null;
		}
	}
	
	/***
	 * 获取PopupWindow实例
	 */
	private void getPopupWindow() {
		if (null != planPopWindow)
		{
			planPopWindow.dismiss();
			return;
		}
		else
		{
			initPopWindow();
		}
	}
	
	@Override
	protected void initAdapter() {
	
	}
	
	@Override
	protected void initDates() {
	
	}
	
	@Override
	protected void initListener() {
		
		findViewById(R.id.rl_plan).setOnClickListener(new View.OnClickListener()
		{
			@Override
			public void onClick(View v) {
				getPopupWindow();
				planPopWindow.showAsDropDown(v, 0, 0);
			}
		});
		
		findViewById(R.id.btn_submit).setOnClickListener(new View.OnClickListener()
		{
			@Override
			public void onClick(View view) {
				String str_zongjie = tv_zongjie.getText().toString();
				String str_workPlane = tv_jihua.getText().toString();
				if (workSummary == null || workSummary.equals(""))
				{
					Util.showToast(getContext(), "请填写" + zongjie_tv.getText().toString());
					return;
				}
				if (workPlan == null || workSummary.equals(""))
				{
					Util.showToast(getContext(), "请填写" + jihua_tv.getText().toString());
					return;
				}
				if (postInfo != null)
				{
					if (str != null && !str.equals(""))
					{
						try
						{
							doRequestHttp(new UploadImgForWorkFlowReq(str));
						}
						catch (Exception e)
						{
							e.printStackTrace();
						}
					}
					else
					{
						doRequestHttp(new submitMyPlanReq(currentType, postInfo.getUserNo() + "", workSummary, "", workPlan, help, remarks, "", ""));
					}
				}
				else
				{
					Toast.makeText(getActivity(), "请选择接受计划人员", Toast.LENGTH_SHORT).show();
				}
			}
		});
		//        findViewById(R.id.rlyt_finish).setOnClickListener(new View.OnClickListener() {
		//            @Override
		//            public void onClick(View view) {
		//                Intent intent = new Intent(getActivity(), FillOutWorkPlaneActivity.class);
		//                intent.putExtra("TYPE", 1);
		//                intent.putExtra("CONTENT", completeWork);
		//                startActivityForResult(intent, 1);
		//            }
		//        });
		findViewById(R.id.rlyt_zongjie).setOnClickListener(new View.OnClickListener()
		{
			@Override
			public void onClick(View view) {
				Intent intent = new Intent(getActivity(), FillOutWorkPlaneActivity.class);
				intent.putExtra("TYPE", 2);
				intent.putExtra("title", zongjie_tv.getText().toString());
				intent.putExtra("CONTENT", workSummary);
				startActivityForResult(intent, 2);
			}
		});
		findViewById(R.id.rlyt_jihua).setOnClickListener(new View.OnClickListener()
		{
			@Override
			public void onClick(View view) {
				Intent intent = new Intent(getActivity(), FillOutWorkPlaneActivity.class);
				intent.putExtra("TYPE", 3);
				intent.putExtra("title", jihua_tv.getText().toString());
				intent.putExtra("CONTENT", workPlan);
				startActivityForResult(intent, 3);
			}
		});
		findViewById(R.id.rlyt_bangzhu).setOnClickListener(new View.OnClickListener()
		{
			@Override
			public void onClick(View view) {
				Intent intent = new Intent(getActivity(), FillOutWorkPlaneActivity.class);
				intent.putExtra("TYPE", 4);
				intent.putExtra("CONTENT", help);
				startActivityForResult(intent, 4);
			}
		});
		findViewById(R.id.rlyt_beizhu).setOnClickListener(new View.OnClickListener()
		{
			@Override
			public void onClick(View view) {
				Intent intent = new Intent(getActivity(), FillOutWorkPlaneActivity.class);
				intent.putExtra("TYPE", 5);
				intent.putExtra("CONTENT", remarks);
				startActivityForResult(intent, 5);
			}
		});
		
		findViewById(R.id.rlyt_chose_btn).setOnClickListener(new View.OnClickListener()
		{
			@Override
			public void onClick(View view) {
				Intent intent = new Intent(getActivity(), ChooseSupActivity.class);
				startActivityForResult(intent, 6);
			}
		});
		
		findViewById(R.id.plane_my_image).setOnClickListener(new View.OnClickListener()
		{
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(getContext(), MultiImageSelectorActivity.class);
				// 是否显示拍摄图片
				intent.putExtra(MultiImageSelectorActivity.EXTRA_SHOW_CAMERA, true);
				// 最大可选择图片数量
				intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_COUNT, PIC_MAX_LENGTH);
				// 选择模式
				intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_MODE, MultiImageSelectorActivity.MODE_SINGLE);
				// 默认选择
				if (selectedPictureAll != null && selectedPictureAll.size() > 0)
				{
					intent.putExtra(MultiImageSelectorActivity.EXTRA_DEFAULT_SELECTED_LIST, selectedPictureAll);
				}
				startActivityForResult(intent, REQUEST_IMAGE);
			}
		});
		
		findViewById(R.id.plan_my_display).setOnClickListener(new View.OnClickListener()
		{
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(getContext(), ImageSeeActivity.class);
				intent.putStringArrayListExtra("urlList", urlList);
				startActivity(intent);
			}
		});
		
		findViewById(R.id.plan_my_delete).setOnClickListener(new View.OnClickListener()
		{
			@Override
			public void onClick(View v) {
				rlImg.setVisibility(View.GONE);
				fujian_iv.setVisibility(View.VISIBLE);
				str = "";
				urlList.clear();
			}
		});
		
	}
	
	@Override
	protected void initHttpRequest() {
	
	}
	
	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		//        ((WorkPlaneActivity)activity).setWorkPlanHandler(workPlanHandler);
	}
	
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == getActivity().RESULT_OK)
		{
			if (requestCode == 1)
			{
				completeWork = data.getStringExtra("cont");
				tv_finish.setText(completeWork + "");
			}
			else if (requestCode == 2)
			{
				workSummary = data.getStringExtra("cont");
				tv_zongjie.setText(workSummary + "");
			}
			else if (requestCode == 3)
			{
				workPlan = data.getStringExtra("cont");
				tv_jihua.setText(workPlan + "");
			}
			else if (requestCode == 4)
			{
				help = data.getStringExtra("cont");
				tv_bangzhu.setText(help + "");
			}
			else if (requestCode == 5)
			{
				remarks = data.getStringExtra("cont");
				tv_beizhu.setText(remarks + "");
			}
			else if (requestCode == 6)
			{
				postInfo = (SelUserPostInfoListEty) data.getSerializableExtra("rusult");
				if (postInfo != null)
				                      tv_plane_man.setText(postInfo.getUserName() + "");
			}
			else if (requestCode == REQUEST_IMAGE)
			{
				mSelectPath = data.getStringArrayListExtra(MultiImageSelectorActivity.EXTRA_RESULT);
//				mSelectPath.removeAll(selectedPictureAll);
				selectedPictureAll.addAll(mSelectPath);
				for (String p : mSelectPath)
				{
					
					Bitmap bitmap = Utils.compressImageFromFile(p);
					imgDisplay.setImageBitmap(bitmap);
					//					Picasso.with(getContext()).load(new File(p)).into(imgDisplay);
					str = p;
				}
				//                try {
				//                    doRequestHttp(new UploadImgForWorkFlowReq(str));
				//                } catch (Exception e) {
				//                    e.printStackTrace();
				//                }
				urlList.add(str);
				fujian_iv.setVisibility(View.GONE);
				rlImg.setVisibility(View.VISIBLE);
			}
		}
	}
	
	@Override
	public void onResponseSuccess(BaseResponse<?> response, String tag) {
		switch (tag) {
			case "UploadImgForWorkFlowReq":
				enclosure = response.getReturnObject().toString();
				doRequestHttp(new submitMyPlanReq(currentType, postInfo.getUserNo() + "", workSummary, "", workPlan, help, remarks, enclosure, ""));
				break;
			case "submitMyPlanReq":
				Toast.makeText(getActivity(), "提交成功", Toast.LENGTH_SHORT).show();
				if (callBack != null)
				                      callBack.submitOk();
				getActivity().finish();
				break;
		}
	}
	
	@Override
	public void onResponseFail(String tag, int resultCode) {
		switch (tag) {
			case "UploadImgForWorkFlowReq":
				Toast.makeText(getActivity(), "附件提交失败", Toast.LENGTH_SHORT).show();
				break;
			case "submitMyPlanReq":
				Toast.makeText(getActivity(), "提交失败", Toast.LENGTH_SHORT).show();
				break;
		}
	}
	
	public void setsubmitPlaneCallBack(submitPlaneCallBack callBack) {
		this.callBack = callBack;
	}
	
	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
		currentType = position + 1;
		hidePopupWindow();
		String name = (String) parent.getAdapter().getItem(position);
		tv_type.setText(name);
		if (name.equals("周报"))
		{
			zongjie_tv.setText("本周工作情况");
			jihua_tv.setText("下周工作计划");
		}
		else if (name.equals("月报"))
		{
			zongjie_tv.setText("本月工作情况");
			jihua_tv.setText("下月工作计划");
		}
		else if (name.equals("季报"))
		{
			zongjie_tv.setText("本季工作情况");
			jihua_tv.setText("下季工作计划");
		}
	}
	
	public interface submitPlaneCallBack
	{
		void submitOk();
	}
	
}
